<?php

define("SITE_PATH",getcwd());
require(SITE_PATH.'/smarty/libs/Smarty.class.php');//绝对路径

//面向对象
class CommonController extends Smarty{

    public $db;

    function __construct()
    {
        parent::__construct();
        $this->smarty_config();
        $this->db_config();
    }

    /**
     * smarty配置
     */
    function smarty_config()
    {
        $this->left_delimiter = "{{";
        $this->right_delimiter = "}}";

        $this->setTemplateDir(SITE_PATH . '/templates/');
        $this->setCompileDir(SITE_PATH . '/templates/templates_c/');
        $this->setConfigDir(SITE_PATH . '/templates/configs/');
        $this->setCacheDir(SITE_PATH . '/templates/cache/');
    }
    /**
     * 数据库配置
     */
    function db_config(){
        $mysqli = new mysqli("127.0.0.1", "root", "", "blog");

        //检查连接错误
        if (mysqli_connect_errno()) {
            exit("连接失败: %s<br>". mysqli_connect_error());
        }
        $mysqli->query("set names utf8");
        $this->db = $mysqli;
    }
    /**
     * 查询所有数据
     */
    function all($sql){
        $res = $this->db->query($sql);
        $arr=[];
        while($row = $res->fetch_assoc()){
            $arr[] = $row;
        }
        return $arr;
    }
    /**
     * 查询单条语句
     */
    function one($sql){
        $res = $this->db->query($sql);
        $row = $res->fetch_assoc();
        return  $row;
    }
    /**
     * 查询数量
     */
    function getNum($sql){
        $res = $this->db->query($sql);
        return $res->num_rows;
    }

    function dump($arr){
        echo '<pre>';
        print_r($arr);
        echo '</pre>';
    }
    /*
     * 删除数据
     */
    function del($sql){
        $this->db->query($sql);
        if ($this->db->affected_rows > 0);
            return true;
    }
    /**
     * 新增数据
     */
    function add($sql){
        $this->db->query($sql);
        if($this->db->affected_rows > 0);
            return true;
    }
    /**
     * 更新数据
     */
    function update($sql){
        $this->db->query($sql);
        if($this->db->affected_rows > 0);
        return true;
    }

    /*
     * 跳转方法
     */
    function redirect($info = null , $url = null){
        if($url == null)
            echo "<script>alert('$info');location=location</script>";
        echo "<script>alert('$info');location.href='$url'</script>";

    }
}